package bg.tu.varna.pms.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;


public class Main {

	final static HashMap<String,Socket> ConnectedClients = new HashMap<String,Socket>();
	static DataBaseHandler DB = null;// = new DataBaseHandler();
	
	public Main(String ip,int prt)
	{
		port = prt;		
		isStarted = false;
		try
		{
			DB = new DataBaseHandler("root","",port,"mype");
            server = new ServerSocket(port);
            System.out.println("Created!");
        }
		catch (IOException | SQLException e) 
		{
            e.printStackTrace();
        }
		
	}
	
	private ServerSocket server;
	private int port;
	private boolean isStarted;
    private ArrayList<SocketHandler> ClientList = new ArrayList<SocketHandler>();
    
    
	public void Start()
	{
		if(!isStarted)
		{
			isStarted = true;
			RunServer();
		}
	}
	
	public void Stop()
	{
		if(isStarted)
		{
			try
			{
				server.close();
				isStarted = false;
			}
			catch(Exception e)
			{
				//da si opravq i drugite exeptioni deto gi saka.
				e.printStackTrace();
			}
		}
	}
	
	private void RunServer()
	{
        System.out.println("Started!");
		while(isStarted)
		{
			try 
			{
	            System.out.println("Waiting...");
				Socket socket = server.accept();
				//Thread trd;
				SocketHandler sock = new SocketHandler(socket);
				//trd = new Thread(sock);
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			catch (Exception e)
			{

			}
		}
		DB.Close();
	}

	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Main obj = new Main("localhost",9999);
		obj.Start();
	}

}
